package com.ljf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljf.dto.EditPswDto;
import com.ljf.dto.EmpPageDto;
import com.ljf.dto.QueryDept;
import com.ljf.entity.Dept;
import com.ljf.entity.Employee;
import com.ljf.entity.Role;
import com.ljf.exception.BusinessException;
import com.ljf.mapper.EmployeeMapper;
import com.ljf.redis.RedisKeys;
import com.ljf.redis.RedisTemplateService;
import com.ljf.service.DeptService;
import com.ljf.service.EmployeeService;
import com.ljf.service.RoleService;
import com.ljf.vo.DetailEmpVo;
import com.ljf.vo.EditEmpVo;
import com.ljf.vo.InformationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private RoleService roleService;

    @Autowired(required = false)
    private DeptService deptService;
    @Override
    public InformationVo information(String token) {
        Employee employee = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class);
        DetailEmpVo vo = detail(employee.getId());
        InformationVo informationVo = new InformationVo();
        BeanUtils.copyProperties(vo,informationVo);
        return informationVo;
    }

    @Override
    public DetailEmpVo detail(Long uid) {
        DetailEmpVo detailEmpVo = new DetailEmpVo();
        //查询员工信息
        Employee employee = super.getById(uid);
        BeanUtils.copyProperties(employee,detailEmpVo);
        //补全角色信息
        Set<String> rolenames = new HashSet<>();
        if (employee.getIsAdmin() == true){
            //查询所有角色
            List<Role> list = roleService.list();
            for (Role role : list){
                rolenames.add(role.getName());
            }
        }else {
            Set<Role> roles = roleService.queryByEid(uid);
            for (Role role : roles){
                rolenames.add(role.getName());
            }
        }
        detailEmpVo.setRoleNames(rolenames);
        return detailEmpVo;
    }

    @Override
    public void saveEmp(Employee employee, String token) {
        //判断参数是否有误
        if (!StringUtils.hasLength(employee.getPassword())){
            employee.setPassword(Employee.DEFAULT_PWD);
        }
        if (!StringUtils.hasLength(employee.getUsername())){
            throw new BusinessException("手机号不能为空");
        }
        if (!StringUtils.hasLength(employee.getIdCard())){
            throw new BusinessException("身份证不能为空");
        }
        if (employee.getAge() == null){
            employee.setAge(18);
        }else if (employee.getAge() < 0 || employee.getAge() > 120){
            throw new BusinessException("年龄数值有误");
        }

        //判断手机号（用户名）是否已经被注册
        Employee employee1 = employeeMapper.getByUsername(employee.getUsername());
        if (employee1 != null){
            throw new BusinessException("用户已经存在");
        }
        employee.setState(Employee.STATE_NORMAL);
        if (!StringUtils.hasText(employee.getSex())){
            employee.setSex(Employee.SEX_MEN);
        }
        if (!StringUtils.hasText(employee.getHeadImg())){
            employee.setHeadImg(Employee.DEFAULT_HEAD_IMG);
        }
        employee.setCreateTime(new Date());
        employee.setIsAdmin(false);
        String nickName = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class).getNickName();
        employee.setCreateby(nickName);
        super.save(employee);
    }

    @Override
    public void updateEmp(Employee employee, String token) {
        if (employee.getState().equals(Employee.STATE_DEL)){
            if (employee.getIsAdmin()){
                throw new BusinessException("不可以给系统管理员办理离职");
            }
        }
        //通过用户名和身份证查询是否已经存在
        /*QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().having("id!="+employee.getId())
                .eq(StringUtils.hasText(employee.getUsername()),"phone",employee.getUsername())
                .or()
                .eq(StringUtils.hasText(employee.getIdCard()),"id_card",employee.getIdCard());
        List<Employee> list = super.list(wrapper);
        if (list!= null && list.size() > 0){
            throw new BusinessException("系统已存在相同的用户名或身份证号");
        }*/
        if (employee.getState().equals(Employee.STATE_DEL)){
            employee.setLeaveTime(new Date());
        }else {
            employee.setCreateTime(new Date());
            String nickName = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class).getNickName();
            employee.setNickName(nickName);
        }
        super.updateById(employee);

    }

    @Override
    public void editPwd(String token, EditPswDto editPswDto) {
        Employee employee = JSONObject.parseObject(redisTemplateService.getCacheObject(token), Employee.class);
        //管理员的密码不能修改
        if (employee.getIsAdmin()){
            throw new BusinessException("该账号不能修改");
        }
        //比对用户名是否一样
        if (!employee.getUsername().equals(editPswDto.getUsername())){
            throw new BusinessException("没有权限修改其他人的密码");
        }
        //whether the old password is correct
        if (!employee.getPassword().equals(editPswDto.getOldPwd())){
            throw new BusinessException("原密码输入有误");
        }
        //whether the new pwd equals the old pwd
        if (editPswDto.getNewPwd().equals(employee.getPassword())){
            throw new BusinessException("新密码和旧密码一致");
        }

        UpdateWrapper<Employee> wrapper = new UpdateWrapper<Employee>()
                .set("password",editPswDto.getNewPwd())
                .eq("phone",editPswDto.getUsername());
        super.update(wrapper);
    }

    @Override
    public Page<Employee> pageEmp(EmpPageDto empPageDto) {
        Page<Employee> page = new Page<>(empPageDto.getCurrentPage(),empPageDto.getPageSize());
        QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>()
                .like(StringUtils.hasText(empPageDto.getUsername()),"phone",empPageDto.getUsername())
                .eq(StringUtils.hasText(empPageDto.getAge()),"age",empPageDto.getAge())
                .like(StringUtils.hasText(empPageDto.getNickName()),"nick_name",empPageDto.getNickName())
                .like(StringUtils.hasText(empPageDto.getAddress()),"address",empPageDto.getAddress())
                .eq(StringUtils.hasText(empPageDto.getSex()),"sex",empPageDto.getSex())
                .ne("id",1L)
                .eq(empPageDto.getDeptId() != null,"deptId",empPageDto.getDeptId());
        super.page(page,wrapper);
        //补全部门信息
        List<Dept> depts = deptService.listBydto(new QueryDept());
        List<Employee> records = page.getRecords();
        if (records != null){
            for (Employee employee : records){
                if (depts != null){
                    for (Dept dept : depts){
                        if (dept.getId().equals(employee.getId())){
                            employee.setDeptName(dept.getName());
                            break;
                        }
                    }
                }
            }
        }
        return page;
    }

    @Override
    public EditEmpVo editbtn(Long uid) {
        EditEmpVo vo = new EditEmpVo();
        Employee employee = super.getById(uid);
        BeanUtils.copyProperties(employee,vo);
        return vo;
    }

    /**
     * 重置密码
     * @param eid
     * @param code
     */
    @Override
    public void resetPwd(Long eid, String code) {
        Employee employee = super.getById(eid);
        if (employee.getId() == 1L) {
            throw new BusinessException("该账户不可被修改");
        }
        if (employee.getIsAdmin()) {
            if (code.equals("123456")) {
                UpdateWrapper<Employee> wrapper = new UpdateWrapper<Employee>().set("password", Employee.DEFAULT_PWD).eq("id", eid);
                super.update(wrapper);
            } else {
                throw new BusinessException("密钥错误");
            }
        } else {
            if (code.equals("456789")) {
                UpdateWrapper<Employee> wrapper = new UpdateWrapper<Employee>().set("password", Employee.DEFAULT_PWD).eq("id", eid);
                super.update(wrapper);
            } else {
                throw new BusinessException("密钥错误");
            }
        }
        redisTemplateService.deleteObject(RedisKeys.LOGIN_USER.join(employee.getUsername()));
        redisTemplateService.deleteObject(RedisKeys.DISABLEUSER.join(employee.getUsername()));
        redisTemplateService.deleteObject(RedisKeys.LOGIN_ERRO_PWDNUM.join(employee.getUsername()));
    }

    @Override
    public void deactivate(Long id) {
        Employee employee = super.getById(id);
        if (employee.getIsAdmin()){
            throw new BusinessException("不能给系统管理员办理离职");
        }
        if (employee.getState().equals(Employee.STATE_DEL)){
            throw new BusinessException("已是离职状态");
        }
        UpdateWrapper<Employee> wrapper = new UpdateWrapper<Employee>().set("state",Employee.STATE_DEL).eq("id",id);
        super.update(wrapper);
    }
}
